package sword.offer;

import java.util.ArrayList;
import java.util.List;

/**
 * 定义栈的数据结构，请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中，调用 min、push 及 pop 的时间复杂度都是 O(1)。
 *
 * @author 胡宇轩
 * @link https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/
 * @Email: yuxuan.hu01@bianlifeng.com
 */
public class Thirty {
    public static void main(String[] args) {
        MinStack minStack = new MinStack();
        minStack.push(2);
        minStack.push(0);
        minStack.push(3);
        minStack.push(0);

        System.out.println(minStack.min());
        minStack.pop();
        System.out.println(minStack.min());
        minStack.pop();
        System.out.println(minStack.min());
        minStack.pop();
        System.out.println(minStack.min());
    }
}

class MinStack {
    List<Integer> data = new ArrayList<>();
    List<Integer> smallStack = new ArrayList<>();

    /**
     * initialize your data structure here.
     */
    public MinStack() {

    }

    public void push(int x) {
        if(smallStack.isEmpty() || x <= smallStack.get(smallStack.size()-1)){
            smallStack.add(x);
        }
        data.add(x);
    }

    public void pop() {
        if(data.get(data.size()-1).equals(smallStack.get(smallStack.size()-1))){
            smallStack.remove(smallStack.size()-1);
        }
        data.remove(data.size()-1);
    }

    public int top() {
        return data.isEmpty() ? 0 : data.get(data.size()-1);
    }

    public int min() {
        return smallStack.isEmpty() ? 0 : smallStack.get(smallStack.size()-1);
    }
}